#!/bin/bash
#
# description: mainland Server Script
# processname: mainLand server
#
# DATE:2018-11-06
# Version:V1.0
#

shopt -u expand_aliases
source /etc/profile

project_dir="$( cd "$( dirname "$0"  )" && pwd  )"
project_name=`echo ${project_dir} | awk -F'/' '{print $NF}'`
project_conf="${project_dir}/game_server.conf"

gcDir=${project_dir}/log4j2/gc
errDir=${project_dir}/log4j2/error

export $(grep srvDB_port ${project_conf})
export $(grep srvWorld0_port ${project_conf})

timeout=120

[[ -d ${gcDir} ]] || mkdir -p ${gcDir}
[[ -d ${errDir} ]] || mkdir -p ${errDir}
find ${project_dir}/log4j2/ -name *.log -mtime +30 -exec rm -rfv {} \;

base_check(){
	for new_file in `ls ${project_dir}/config | grep properties`;do
		echo "Create ${project_dir}/config/${new_file}..."
		dos2unix ${project_dir}/config/${new_file}
		cat ${project_dir}/config/${new_file} | grep -Ev "^$|^[#;]" | while read line;do
			key=`echo ${line} | awk -F"=" '{print $1}'`
			base_conf=`cat ${project_conf} | grep ^${key} | grep -Ev "^$|^[#;]" `
			if [ ! -z ${base_conf} ];then
				if [ "${base_conf}" == "${line}" ] ;then
					echo "${line}" >> ${project_dir}/config/${new_file}.new
				else
					echo "${base_conf}" >> ${project_dir}/config/${new_file}.new
				fi
			else
				echo "${line}" >> ${project_dir}/config/${new_file}.new
			fi
		done
		rm -f ${project_dir}/config/${new_file} && mv ${project_dir}/config/${new_file}.new ${project_dir}/config/${new_file}
		echo "${project_dir}/config/${new_file} Generate complete."
	done
}

genDB(){
	cd ${project_dir} || ( echo "${project_dir} Not exist. ";exit 0)
	#生成新的文件（生成前会判断是否能够生成，然后在清除旧文件重新生成） 参数：待生成源包路径  生成目标文件夹
	echo "Run genDB..."
	java -cp ./config/:./plant/json:./plant/nameFix:./main/*:./plant/stageConfig:./libs/* org.gof.core.gen.entity.GenDB org.gof false true ./main/world-1.0.jar
	if [ $? -eq 0 ];then
		echo "genDB Run Succeed."
	else
		echo "genDB Run Fail."
	fi
}

srvDB(){
	srvName=${project_name}_DB
	runParam1=
	#设置加载类的环境变量 运行主类名
	CPATH="./config/:./plant/json:./plant/nameFix:./main/*:./libs/*"
	MAIN="org.gof.core.dbsrv.main.DBStartup"
	#设置运行参数
	javaParam="-server -Xms1024m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -XX:MaxDirectMemorySize=512m"
	javaParam="${javaParam} -XX:+AlwaysLockClassLoader -XX:+UseG1GC -XX:MaxGCPauseMillis=150 -XX:+UseStringDeduplication"
	javaParam="${javaParam} -XX:+PrintGCDateStamps -XX:+PrintGCDetails -verbose:gc -Xloggc:${gcDir}/${srvName}_gc.log"
	javaParam="${javaParam} -XX:ErrorFile=${errDir}/${srvName}_error_%p.log -XX:HeapDumpPath=${errDir}/${srvName}_heapDump_%p.hprof"
	eval \"java\" ${javaParam} -cp \"${CPATH}\" \"${MAIN}\" \"${runParam1}\"
}

srvWorld0(){
	srvName=${project_name}_srvWorld0
	runParam1=0
	#设置加载类的环境变量 运行主类名
	CPATH="./config/:./plant/json:./plant/nameFix:./libs/*:./main/lz-1.0.jar"
	MAIN="org.gof.demo.seam.main.WorldStartup"
	#设置运行参数
	javaParam="-server -Xms7168m -Xmx7168m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -XX:MaxDirectMemorySize=1024m"
	javaParam="${javaParam} -XX:+AlwaysLockClassLoader -XX:+UseG1GC -XX:MaxGCPauseMillis=150 -XX:+UseStringDeduplication"
	javaParam="${javaParam} -XX:+PrintGCDateStamps -XX:+PrintGCDetails -verbose:gc -Xloggc:${gcDir}/${srvName}_gc.log"
	javaParam="${javaParam} -XX:ErrorFile=${errDir}/${srvName}_error_%p.log -XX:HeapDumpPath=${errDir}/${srvName}_heapDump_%p.hprof"
	javaParam="${javaParam} -javaagent:libs/classReloader.jar"
	eval \"java\" ${javaParam} -cp \"${CPATH}\" \"${MAIN}\" \"${runParam1}\"
}

start(){
	cd ${project_dir}
	#srvDB_PID=`lsof -i:${srvDB_port} | grep LISTEN | awk '{print $2}'`
	srvDB_PID=`netstat -anlp|grep ${srvDB_port} | grep LISTEN | awk '{printf $7}'|cut -d/ -f1`
	if [ ! -z "$srvDB_PID" ];then
		echo "srvDB Port:${srvDB_port} Listening. "
		#srvWorld0_PID=`lsof -i:${srvWorld0_port} | grep LISTEN | awk '{print $2}'`
		srvWorld0_PID=`netstat -anlp|grep ${srvWorld0_port}| grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
		if [ ! -z "$srvWorld0_PID" ];then
			echo -e "srvWorld Port:${srvWorld0_port}  Listening. "
			exit 1
		else
			wait_time=
			echo -en "Start srvWorld0 "
			srvWorld0  >/dev/null 2>&1 &
			while true;do
				if [ "$(netstat -ntl | grep :${srvWorld0_port})" != "" ]; then
					echo -en "[OK] \n"
					exit 1
				elif [ "${timeout}" == "${wait_time2}" ];then
					echo -en "[Fail] \n"
					exit 0
				else
					echo -en "." 
					sleep 1
				fi
				((wait_time++))   
			done
		fi
	else
		wait_time=
		echo -en "Start srvDB "
		srvDB >/dev/null 2>&1 &
		while true;do
			if [ "$(netstat -ntl | grep :${srvDB_port})" != "" ]; then
				echo -en "[OK] \n"
				#srvWorld0_PID=`lsof -i:${srvWorld0_port} | grep LISTEN | awk '{print $2}'`
				srvWorld0_PID=`netstat -anlp|grep ${srvWorld0_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
				if [ ! -z "$srvWorld0_PID" ];then
					echo -e "srvWorld Port:${srvWorld0_port} Listening. "
					exit 0
				else
					wait_time2=
					echo -en "Start srvWorld0 "
					srvWorld0 >/dev/null 2>&1 &
					while true;do
						if [ "$(netstat -ntl | grep :${srvWorld0_port})" != "" ]; then
							echo -en "[OK] \n"
							exit 1
						elif [ "${timeout}" == "${wait_time2}" ];then
							echo -en "[Fail] \n"
							exit 0
						else
							echo -en "." 
							sleep 1
						fi
						((wait_time2++))   
					done
				fi
			elif [ "${timeout}" == "${wait_time}" ];then
            	echo -en "[Fail] \n"
                break
			else     
				sleep 1
                echo -en "." 
			fi
            ((wait_time++))   
          done
	fi
	exit 1
}

stop_srvDB(){
	#srvDB_PID=`lsof -i:${srvDB_port} | grep LISTEN | awk '{print $2}'`
	srvDB_PID=`netstat -anlp|grep ${srvDB_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	echo -en "Stop srvDB PID(${srvDB_PID}) "
	if [ ! -z ${srvDB_PID} ];then
		kill -15 ${srvDB_PID} 2>&1 >/dev/null &
		while true;do
			if [ "$(netstat -ntl | grep :${srvDB_port})" != "" ]; then
				echo -en "."
				sleep 1
			else
				echo -en "[OK] \n"
				break
			fi
		done
	else
		echo -en "\n srvDB Not Runing. \n"
	fi
}

stop_srvWorld0(){
	#srvWorld0_PID=`lsof -i:${srvWorld0_port} | grep LISTEN | awk '{print $2}'`
	srvWorld0_PID=`netstat -anlp|grep ${srvWorld0_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	echo -en "Stop srvWorld0 PID(${srvWorld0_PID}) "
	if [ ! -z ${srvWorld0_PID} ];then
		kill -15 ${srvWorld0_PID} >/dev/null 2>&1 &
		while true;do
			if [ "$(netstat -ntl | grep :${srvWorld0_port})" != "" ]; then
				echo -en "."
				sleep 1
			else
				echo -en "[OK] \n"
				break
			fi
		done
	else
		echo -en "\n srvWorld0 Not Runing. \n"
	fi
}

stop(){
	if [ "$1" = "all" ];then
		stop_srvWorld0
		stop_srvDB
	else
		stop_srvWorld0
	fi
}


killer(){
	#srvDB_PID=`lsof -i:${srvDB_port} | grep LISTEN | awk '{print $2}'`
	srvDB_PID=`netstat -anlp|grep ${srvDB_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	#srvWorld0_PID=`lsof -i:${srvWorld0_port} | grep LISTEN | awk '{print $2}'`
	srvWorld0_PID=`netstat -anlp|grep ${srvWorld0_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	if [ "$1" = "all" ];then
		echo -e "\033[31m Kill srvDB and srvWorld0 . \033[0m"
		read -p "Sure you want to kill all server?   " affirm
		if [ "$affirm" = "Y" -o "$affirm" = "y" -o "$affirm" = "Yes" -o "$affirm" = "yes" -o "$affirm" = "YES" ];then
			if [ ! -z "${srvWorld0_PID}" ];then
				kill -9 ${srvWorld0_PID}
				echo -e "\033[33m Kill srvWorld0 OK. \033[0m"
			else
				echo -e "\033[31m srvDB Not Runing. \033[0m"
			fi
			if [ ! -z "${srvDB_PID}" ];then
				kill -9 ${srvDB_PID}
				echo -e "\033[33m Kill srvDB OK. \033[0m"
			else
				echo -e "\033[31m srvDB Not Runing. \033[0m"
			fi
		else
			echo -e "\033[31m Parameter error.\033[0m"
		fi
	else
		echo -e "\033[31m Kill srvWorld0. \033[0m"
		if [ ! -z "${srvWorld0_PID}" ];then
			kill -9 ${srvWorld0_PID} 
			echo -e "\033[33m Kill srvWorld0 OK. \033[0m"
		else
			echo -e "\033[31m srvWorld0 Down. \033[0m"
		fi
	fi
}

status(){
	#srvDB_PID=`lsof -i:${srvDB_port} | grep LISTEN | awk '{print $2}'`
	srvDB_PID=`netstat -anlp|grep ${srvDB_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	if [ ! -z "$srvDB_PID" ];then
		echo "srvDB Port: ${srvDB_port} Listen."
		echo "PID: ${srvDB_PID}"
		echo "Start Time: `ps -p ${srvDB_PID} -o lstart | grep -v "START"`"
		netstat -n|grep :${srvDB_port} | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
	else
		echo "srvDB Port: ${srvDB_port} Down."
	fi

	#srvWorld0_PID=`lsof -i:${srvWorld0_port} | grep LISTEN | awk '{print $2}'`
	srvWorld0_PID=`netstat -anlp|grep ${srvWorld0_port}|grep LISTEN |awk '{printf $7}'|cut -d/ -f1`
	if [ ! -z "$srvWorld0_PID" ];then
		echo "srvWorld0 Port: ${srvWorld0_port} Listen."
		echo "PID: ${srvWorld0_PID}"
		echo "Start Time: `ps -p ${srvWorld0_PID} -o lstart | grep -v "START"`"
		netstat -n|grep :${srvWorld0_port} | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
	else
		echo "srvWorld0 Port: ${srvWorld0_port} Down."
	fi
}


case "$1" in
	start)
		start
	;;
	genDB)
		genDB
	;;
	srvDB)
		srvDB &
	;;
	srvWorld0)
		srvWorld0 &
	;;
	stop)
		stop $2
	;;
	stop_all)
		stop all
	;;
	stop_srvDB)
		stop_srvDB
	;;
	killer)
		killer $2
	;;
	restart)
		stop $2
		start
	;;
	status)
		status
	;;
	check)
		base_check 
	;;
	*)
	echo $"Usage: $0 {start|genDB|srvDB|srvWorld0|stop_srvDB|status|check}"
	echo $"Usage: $0 {stop|stop_all|killer|restart [all]}"
	exit 2
esac
